package StudyCode.summary.myfile;

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CopyDirectoryWithSimpleFileVisitor {
	public static void main(String[] args) {
		try {
			Path source = Paths.get("E:/Copy");
			Path target = Paths.get("E:/Move");
			Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, new CopyDirectorySimpleFileVisitor(source, target));
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}

}

class CopyDirectorySimpleFileVisitor extends SimpleFileVisitor<Path> {
	private Path source;
	private Path target;

	public CopyDirectorySimpleFileVisitor(Path source, Path target) {
		this.source = source;
		this.target = target;
	}

	@Override
	public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
			throws IOException {
		System.out.println("复制中: " + source.relativize(file));
		Files.copy(file, target.resolve(source.relativize(file)));
		return FileVisitResult.CONTINUE;

	}

	@Override
	public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
		Path targetDirectory = target.resolve(source.relativize(directory));
		try {
			System.out.println("复制中: " + source.relativize(directory));
			Files.copy(directory, targetDirectory);
		} catch (FileAlreadyExistsException e) {
			if (!Files.isDirectory(targetDirectory)) {
				throw e;
			}
		}
		return FileVisitResult.CONTINUE;
	}
}
